import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtCore import QTimer, QTime


class StopwatchUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 创建布局和控件
        layout = QVBoxLayout()
        self.label = QLabel()
        self.start_button = QPushButton('Start')
        self.stop_button = QPushButton('Stop')
        self.reset_button = QPushButton('Reset')

        # 设置按钮事件处理函数
        self.start_button.clicked.connect(self.start)
        self.stop_button.clicked.connect(self.stop)
        self.reset_button.clicked.connect(self.reset)

        # 添加控件到布局中
        layout.addWidget(self.label)
        layout.addWidget(self.start_button)
        layout.addWidget(self.stop_button)
        layout.addWidget(self.reset_button)

        # 设置窗口属性和显示
        self.setLayout(layout)
        self.setWindowTitle('Stopwatch')
        self.show()

    def start(self):
        # 创建定时器并启动
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)  # 每秒更新一次时间

    def stop(self):
        # 停止定时器
        if self.timer:
            self.timer.stop()

    def reset(self):
        # 重置时间并停止定时器
        self.label.setText('00:00:00')
        self.stop()

    def update_time(self):
        # 更新时间显示
        current_time = QTime().addSecs(1)  # 增加一秒
        self.label.setText(current_time.toString('mm:ss:zz'))  # 格式化为分钟:秒:毫秒


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = StopwatchUI()
    sys.exit(app.exec_())
